<template>
  <div class="wisdom-rolling-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="device-content">
        <h4 class="title">设备情况</h4>
        <div class="search-content">
          <el-select
            :popper-append-to-body="false"
            v-model="currentId"
            filterable
            placeholder="请选择项目">
            <el-option
              v-for="item in projectList"
              :key="item.projectId"
              :label="`${item.projectName}${item.projectAddress ? `(${item.projectAddress})` : ''}`"
              :value="item.projectId">
              {{ item.projectName }}
              {{ item.projectAddress ? `(${item.projectAddress})` : '' }}
            </el-option>
          </el-select>
        </div>
<!--        <p class="device-num">当前设备在线数量：{{ onlineNum }} 台</p>-->
        <div class="area-list">
          <el-tree
            ref="tree"
            highlight-current
            :current-node-key="levelId"
            :data="areaData"
            :props="{
              children: 'levels',
              label: 'name'
            }"
            node-key="id"
            @node-click="handleClick">
          </el-tree>
        </div>
      </div>
<!--      <div class="map-content" id="map-box"></div>-->
      <div class="map-content">
        <div class="btns">
          <el-button type="primary" :disabled="!this.mileageId" @click="getRealData">
            实时数据
          </el-button>
          <el-button type="primary" :disabled="!dataserias.length" @click="replay">
            轨迹回放
          </el-button>
        </div>
        <div class="echarts-content">
          <div :class="['color-list', hasShow ? 'show' : 'hide']">
            <div class="color-btn roll_num" @click="handleSet">
              <i class="el-icon-right"></i>
            </div>
            <div
              class="roll_num"
              v-for="(item, index) in colors"
              :style="{'background-color':item }"
              :key="index">
              第{{ index + 1 }}遍
            </div>
          </div>
          <div id="hotChart" v-show="!isReplay"></div>
          <div id="replayChart" v-show="isReplay"></div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';

export default {
  components: {
    Breadcrumb,
  },
  data() {
    return {
      breadcrumbData: [
        {
          name: '质量管理',
        },
        {
          name: '智慧碾压'
        }
      ],
      dateTime: 12,
      hasShow: true,
      deviceList: [],
      currentId: '', // 当前项目ID
      projectList: [],
      areaData: [],
      levelId: '', // 层数Id
      mileageId: '', // 里程Id
      colors: ['#FFD0FF', '#F6AAFF', '#E58BFF', '#CE72FF', '#B15EFF', '#914DFF', '#7749FF', '#624FFF', '#515DFF', '#4372FF', '#378DFF', '#2EA2F6', '#26B4E5', '#20C2CE', '#1BCDB1', '#17D691', '#1DDE77', '#2CE462', '#41E951', '#5CED43'],
      lineWidth: this.$setRem(20, false),
      loadFinish: true,// 上面的数据加载是否完成
      chart: null,
      isReplay: false,
      dataserias: [],
      replayFlag: 0,
      rtks: [], // rtk原始坐标点
      minMaxPoint: [],// 转换后极点坐标，长度为4分别为：最小经度，最小纬度，最大经度，最大纬度
      cevInfo: [], // 存放cev的统计数据
      cevDatas: [], // 用来接收上面的数据，需要倒腾一遍子组件才能接收
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    onlineNum() {
      return this.deviceList.length;
    },
    // 当前项目信息
    currentData() {
      return this.projectList.find(v => (
        v.projectId === this.currentId
      )) || {};
    },
    // 当前区域信息
    currentArea() {
      return this.areaData.find(v => (
        v.mileageId === this.mileageId
      )) || {};
    }
  },
  watch: {
    currentId(val) {
      if (val) {
        this.getIcccMileageTree({
          projectNo: val // 项目id
        });
      }
    },
    levelId(val) {
      if (val) {
        this.getIcccDetectDatas();
      }
    },
  },
  async created() {
    await this.icccLogin();
    this.getIcccList();
  },
  methods: {
    // 登录
    async icccLogin() {
      await this.$Model.icccLogin({
        projectId: this.projectId
      });
    },
    // 获取碾压设备列表
    async getIcccList() {
      const params = {
        projectId: this.projectId,
      };
      const { success, data: {
        data
      }} = await this.$Model.getIcccList(params);
      if (success && data && data.values) {
        this.projectList = data.values || [];
        if (!this.currentId) {
          this.currentId = this.projectList[0]
            ? this.projectList[0].projectId
            : '';
        }
      }
    },
    // 获取区域层级树形结构
    async getIcccMileageTree(options = {}) {
      const params = {
        projectId: this.projectId,
        ...options
      };
      const { success, data: {
        data
      }} = await this.$Model.getIcccMileageTree(params);
      if (success && data && data.values) {
        const values = data.values || [];
        this.areaData = values.map(item => {
          const { levels, mileageName, mileageId } = item;
          return {
            id: mileageId,
            name: mileageName,
            ...item,
            levels: levels && levels.map(v => ({
              ...v,
              id: `${mileageId}_${v.levelId}`,
              name: `${mileageName}（${v.levelNum}）`
            }))
          };
        });
      }
    },
    // 根据层数id获取rtk数据
    async getIcccDetectDatas(options = {}) {
      const params = {
        projectId: this.projectId,
        levelId: this.levelId,
        ...options
      };
      const { success, data: {
        data
      }} = await this.$Model.getIcccDetectDatas(params);
      if (success && data && data.values) {
        const { rtk } = data.values;
        this.setRtks(rtk);
      }
    },
    // 获取碾压设备实时数据
    async getIcccRecive(options = {}) {
      if (!this.mileageId) {
        this.$message.warning('请选择有效区域');
        return;
      }
      const params = {
        pid: this.mileageId,
        dateTime: this.dateTime,
        projectId: this.projectId,
        ...options
      };
      const { success, data: {
        data
      }} = await this.$Model.getIcccRecive(params);
      if (success && data) {
        console.log('获取碾压设备实时数据', data);
        const { rtk } = data.values;
        this.setRtks(rtk);
      }
    },
    handleSet() {
      this.hasShow = !this.hasShow;
    },
    handleClick({ mileageId, levelId }) {
      if (!levelId) {
        this.$message.warning('请选择子节点');
      }
      this.mileageId = mileageId || '';
      this.levelId = levelId || '';
    },
    // 获取实时数据
    getRealData() {
      this.getIcccRecive();
    },
    // 设置rtk数据
    setRtks(rtks) {
      if (!rtks || !rtks.length) {
        this.$message.warning('暂无历史数据');
        return;
      }
      let minLat = 1000000000000;
      let minLon = 1000000000000;
      let maxLat = 0;
      let maxLon = 0;
      // 计算面积测试
      // const points = [];
      rtks.forEach(val => {
        // points.push([val.longitude, val.lat]); // 计算面积用的
        // let area = AMap.GeometryUtil.ringArea(points);
        this.countCev(val); // 计算cev平均值
        const lat = (Math.log(Math.tan((90 + val.lat) * Math.PI / 360)) / (Math.PI / 180)) * 20037508.34 / 180;
        const longitude = val.longitude * 20037508.34 / 180;
        val.transLat = lat;
        val.transLongitude = longitude;
        if (lat > maxLat) maxLat = lat;
        if (lat < minLat) minLat = lat;
        if (longitude > maxLon) maxLon = longitude;
        if (longitude < minLon) minLon = longitude;
      });
      this.rtks = rtks;
      this.minMaxPoint = [minLat, minLon, maxLat, maxLon];
      this.cevDatas = this.cevInfo;
      this.setSeral();
    },
    // 回放
    replay () {
      this.isReplay = !this.isReplay;
      setTimeout(() => {
        this.replayICCCLine(this.dataserias);
      }, 30);
    },
    // 画图
    setSeral () {
      const serials = [];
      for (let j = 0; j < this.rtks.length; j++) {
        this.rtks[j].transMinLat = this.rtks[j].transLat - this.minMaxPoint[0];
        this.rtks[j].transMinLongitude = this.rtks[j].transLongitude - this.minMaxPoint[1];
        // 直接用层数画点
        if (j >= 3) {
          const serial = {
            type: 'line',
            data: [
              [this.rtks[j - 2].transMinLongitude, this.rtks[j - 2].transMinLat],
              [this.rtks[j - 1].transMinLongitude, this.rtks[j - 1].transMinLat],
              [this.rtks[j].transMinLongitude, this.rtks[j].transMinLat]
            ],
            itemStyle: {
              color: this.colors[this.rtks[j].levelNum > 20 ? 19 : this.rtks[j].levelNum]
            },
            lineStyle: {
              width: this.lineWidth
            },
            symbol: 'none'
          };
          serials.push(serial);
        }
      }
      this.dataserias = serials;
      this.drawICCCLine(serials);
    },
    drawICCCLine (serias) {
      const icccOption = {
        xAxis: {
          show: false,
          axisLine: { show: false },
          minorTick: { show: false },
          axisTick: {
            show: false, // 是否显示刻度
          },
          // min: this.minlong_echarts,
          // max: this.maxlong_echarts,
          type: 'value'
        },
        yAxis: {
          show: false,
          // min: this.minlat_echarts,
          // max: this.maxlat_echarts,
          axisTick: {
            show: false, // 是否显示刻度
          },
          type: 'value'
        },
        tooltip: {
          show: false
        },
        grid: {
          top: '10px',
          left: '10px',
          right: '30px',
          bottom: '30px',
          containLabel: false
        },
        animation: false,
        series: serias,
      };
      if (!this.chart) {
        this.chart = this.$echarts.init(document.getElementById('hotChart'));
      } else this.chart.clear();
      this.chart.setOption(icccOption);
    },
    replayICCCLine (serias) {
      if (this.replayFlag > serias.length) return;
      const scatterSerias = [
        {
          type: 'scatter',
          symbolSize: 20,
          symbol: 'circle',
          zlevel: 1,
          data: [serias[this.replayFlag].data[0]],
          itemStyle: {
            color: 'green',
            opacity: 1
          }
        },
        {
          type: 'scatter',
          symbolSize: 15,
          symbol: 'circle',
          zlevel: 2,
          data: [serias[this.replayFlag].data[1]],
          itemStyle: {
            color: 'yellow',
            opacity: 1
          }
        }, {
          type: 'scatter',
          symbolSize: 10,
          zlevel: 3,
          symbol: 'circle',
          data: [serias[this.replayFlag].data[2]],
          itemStyle: {
            color: 'red',
            opacity: 1
          }
        }];
      const showArray = serias.slice(0, this.replayFlag);
      const allPoint = scatterSerias.concat(showArray);
      this.replayFlag++;
      const icccOption = {
        xAxis: {
          show: false,
          axisLine: { show: false },
          minorTick: { show: false },
          axisTick: {
            show: false, // 是否显示刻度
          },
          // min: this.minlong_echarts,
          // max: this.maxlong_echarts,
          type: 'value'
        },
        yAxis: {
          show: false,
          // min: this.minlat_echarts,
          // max: this.maxlat_echarts,
          axisTick: {
            show: false, // 是否显示刻度
          },
          type: 'value'
        },
        tooltip: {
          show: false
        },
        grid: {
          top: '10px',
          left: '10px',
          right: '30px',
          bottom: '30px',
          containLabel: false
        },
        animation: false,
        series: allPoint
      };
      if (!this.replayChart) {
        this.replayChart = this.$echarts.init(document.getElementById('replayChart'));
      }
      this.replayChart.setOption(icccOption);
      setTimeout(() => {
        this.replayICCCLine(serias);
      }, 50);
    },
    countCev({ levelNum, cev }) {
      if (!this.cevInfo[levelNum]) {
        this.cevInfo[levelNum] = [levelNum, cev, 1];
      } else {
        this.cevInfo[levelNum][1] = this.cevInfo[levelNum][1] + cev;
        this.cevInfo[levelNum][2] = this.cevInfo[levelNum][2] + 1;
      }
    },
  }
};
</script>

<style lang="scss" scoped>
  @import '../../../assets/styles/main';

  .wisdom-rolling-page {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: $baseBg;
    main {
      width: 100%;
      height: calc(100% - 40px);
      padding: 20px;
      display: flex;
      justify-content: space-between;
      border-radius: 10px;
      .device-content {
        width: 450px;
        height: 100%;
        display: flex;
        flex-direction: column;
        padding: 20px;
        transition: all .3s;
        background-color: $mainBg;
        text-align: center;
        &.show {
          transform: translateX(0);
        }
        &.hide {
          transform: translateX(-100%);
        }
        .el-select {
          width: 80%;
          margin-bottom: 20px;
        }
        .title {
          margin-bottom: 10px;
        }
        .area-list {
          margin-top: 20px;
          width: 100%;
          height: calc(100% - 140px);
          .el-tree {
            height: 100%;
            overflow: auto;
            background: $mainBg;
            color: #fff;
            /deep/ .el-tree-node__content {
              height: 40px;
              &:hover {
                color: $mainColor;
                background: transparent;
              }
            }
          }
          .el-tree {
            /deep/ .el-tree-node.is-current > .el-tree-node__content {
              color: $mainColor;
              background: $baseBg;
            }
            /deep/ .el-tree-node.is-focusable:not(.is-current) > .el-tree-node__content {
              background: transparent;
            }
          }
          .area-item {
            width: 100%;
            height: 45px;
            line-height: 45px;
            background: $lightBtnBg;
            border-radius: 10px;
            margin-bottom: 20px;
            cursor: pointer;
            transition: background .3s;
            &.active {
              background: $mainBtnBg;
            }
          }
        }
      }
      .map-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        background: $mainBg;
        .btns {
          width: 100%;
          height: 60px;
          display: flex;
          justify-content: flex-end;
          align-items: center;
          padding: 0 20px;
        }
        .echarts-content {
          width: 100%;
          height: calc(100% - 50px);
          background: #fff;
          position: relative;
          overflow: hidden;
          > div {
            width: 100%;
            height: 100%;
            &.color-list {
              width: 100px;
              position: absolute;
              top: 50px;
              right: 0;
              display: flex;
              flex-direction: column;
              transition: all .3s;
              z-index: 1;
              &.show {
                transform: translateX(0%);
              }
              &.hide {
                transform: translateX(100%);
                .color-btn {
                  transform: translateX(-100%);
                  width: 50%;
                  .el-icon-right {
                    transform: rotate(-180deg);
                  }
                }
              }
              .color-btn {
                transition: all .4s;
                background-color: #f5def5;
                .el-icon-right {
                  font-size: 20px;
                  cursor: pointer;
                }
              }
              .roll_num {
                width: 100%;
                height: 30px;
                line-height: 30px;
                text-align: center;
                font-weight: 500;
              }
            }
          }
        }
      }
    }
  }
</style>
